package com.smart.community.property.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.community.commons.annotation.ApiLog;
import com.smart.community.commons.enums.ApiLogOperationType;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.property.entity.PermissionAuditLog;
import com.smart.community.property.service.IPermissionAuditLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 权限审计日志控制器
 * @author Wu.Liang
 * @since 2025-07-01
 */
@Slf4j
@RestController
@RequestMapping("/property/audit-logs")
@Tag(name = "权限审计日志", description = "权限审计日志相关接口")
public class PermissionAuditLogController {

    @Autowired
    private IPermissionAuditLogService permissionAuditLogService;

    /**
     * 分页查询权限审计日志
     */
    @GetMapping
    @Operation(summary = "分页查询权限审计日志", description = "支持按条件查询权限审计日志")
    public Result<PageResult<PermissionAuditLog>> getAuditLogPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "操作类型") @RequestParam(required = false) String operation,
            @Parameter(description = "操作结果：0-失败，1-成功") @RequestParam(required = false) String result,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) throws Exception {
        
        Page<PermissionAuditLog> page = new Page<>(current, size);
        PageResult<PermissionAuditLog> pageResult = permissionAuditLogService.getAuditLogPage(
            page, userId, operation, result, startTime, endTime);
        return Result.success(pageResult);
    }

    /**
     * 获取权限审计日志详情
     */
    @GetMapping("/{logId}")
    @Operation(summary = "获取权限审计日志详情", description = "获取指定权限审计日志的详细信息")
    public Result<PermissionAuditLog> getAuditLogDetail(
            @Parameter(description = "日志ID") @PathVariable Long logId) throws Exception {
        
        PermissionAuditLog auditLog = permissionAuditLogService.getAuditLogDetail(logId);
        if (auditLog == null) {
            return Result.error("审计日志不存在");
        }
        return Result.success(auditLog);
    }

    /**
     * 根据用户ID查询权限审计日志
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "根据用户ID查询权限审计日志", description = "查询指定用户的权限审计日志")
    public Result<List<PermissionAuditLog>> getAuditLogsByUserId(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) throws Exception {
        
        List<PermissionAuditLog> logs = permissionAuditLogService.getAuditLogsByUserId(userId, limit);
        return Result.success(logs);
    }

    /**
     * 根据操作类型查询权限审计日志
     */
    @GetMapping("/operation/{operation}")
    @Operation(summary = "根据操作类型查询权限审计日志", description = "查询指定操作类型的权限审计日志")
    public Result<List<PermissionAuditLog>> getAuditLogsByOperation(
            @Parameter(description = "操作类型") @PathVariable String operation,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) throws Exception {
        
        List<PermissionAuditLog> logs = permissionAuditLogService.getAuditLogsByOperation(operation, limit);
        return Result.success(logs);
    }

    /**
     * 获取权限审计统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取权限审计统计信息", description = "获取权限审计相关的统计信息")
    public Result<Map<String, Object>> getAuditStatistics(
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) throws Exception {
        
        Map<String, Object> statistics = permissionAuditLogService.getAuditStatistics(startTime, endTime);
        return Result.success(statistics);
    }

    /**
     * 获取权限异常统计信息
     */
    @GetMapping("/exception-statistics")
    @Operation(summary = "获取权限异常统计信息", description = "获取权限异常相关的统计信息")
    public Result<Map<String, Object>> getExceptionStatistics(
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) throws Exception {
        
        Map<String, Object> statistics = permissionAuditLogService.getExceptionStatistics(startTime, endTime);
        return Result.success(statistics);
    }

    /**
     * 获取用户权限操作统计
     */
    @GetMapping("/user-statistics/{userId}")
    @Operation(summary = "获取用户权限操作统计", description = "获取指定用户的权限操作统计信息")
    public Result<Map<String, Object>> getUserOperationStatistics(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "统计天数") @RequestParam(defaultValue = "30") Integer days) throws Exception {
        
        Map<String, Object> statistics = permissionAuditLogService.getUserOperationStatistics(userId, days);
        return Result.success(statistics);
    }

    /**
     * 获取权限审计日志趋势分析
     */
    @GetMapping("/trend-analysis")
    @Operation(summary = "获取权限审计日志趋势分析", description = "获取权限审计日志的趋势分析数据")
    public Result<Map<String, Object>> getAuditTrendAnalysis(
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) throws Exception {
        
        Map<String, Object> trendAnalysis = permissionAuditLogService.getAuditTrendAnalysis(startTime, endTime);
        return Result.success(trendAnalysis);
    }

	@ApiLog(logTitle = "导出权限审计日志", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "导出权限审计日志", description = "导出权限审计日志到Excel文件")
    public Result<String> exportAuditLogs(
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "操作类型") @RequestParam(required = false) String operation,
            @Parameter(description = "操作结果：0-失败，1-成功") @RequestParam(required = false) String result,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) throws Exception {
        
        String filePath = permissionAuditLogService.exportAuditLogs(userId, operation, result, startTime, endTime);
        return Result.success("导出成功", filePath);
    }

	@ApiLog(logTitle = "批量删除权限审计日志", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.DELETE)
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除权限审计日志", description = "批量删除指定的权限审计日志")
    public Result<Boolean> batchDeleteAuditLogs(
            @Parameter(description = "日志ID列表") @RequestBody List<Long> logIds) throws Exception {
        
        boolean success = permissionAuditLogService.batchDeleteAuditLogs(logIds);
        return Result.success(success);
    }

	@ApiLog(logTitle = "清理过期审计日志", logType = 2, // 操作日志
			moduleName = "物业管理", operationType = ApiLogOperationType.DELETE)
    @PostMapping("/clean-expired")
    @Operation(summary = "清理过期审计日志", description = "清理指定天数之前的审计日志")
    public Result<Integer> cleanExpiredLogs(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "90") Integer days) throws Exception {
        
        int deletedCount = permissionAuditLogService.cleanExpiredLogs(days);
        return Result.success("清理成功", deletedCount);
    }
}
